const path = require('path')
const fs = require('fs')

const repair = i => {
    return i.toString().padStart(2, '0')
}
const timeStr = _ => {
    const date = new Date()
    const year = date.getFullYear()
    const month = repair(date.getMonth() + 1)
    const day = repair(date.getDate())
    const hour = repair(date.getHours())
    const minute = repair(date.getMinutes())
    const second = repair(date.getSeconds())

    //当前时间 
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}

const log = txt => {
    console.log(txt)
    const time = timeStr()
    const date = time.split(" ")[0]
    const logPath = path.join(__dirname, '../log')
    const logFile = path.join(logPath, `${date}.log`)

    fs.existsSync(logPath) || fs.mkdirSync(logPath)
    const options = {
        flags: 'a',
        encoding: 'utf8'
    }
    const logStream = fs.createWriteStream(logFile, options)
    // \r\n用于换行
    let logger = new console.Console(logStream);
    if (txt) {
        logger.log(`${time}: `, txt);
    } else {
        logger.log('')
    }
    logger = null
}

module.exports = {
    timeStr,
    log
}

